package QuickPALM;

import java.awt.Rectangle;

import ij.IJ;
import ij.ImagePlus;
import ij.measure.ResultsTable;
import ij.plugin.PlugIn;
import ij.process.ImageProcessor;

/**
 * This plugin creates a 3D information table by observing the width and height
 * change of beads over time (based on astigmatism).
 */

public class Generate_3D_information_division implements PlugIn {
	private ImagePlus imp;
	private ImageProcessor ip;
	
	private MyDialogs dg = new MyDialogs();
	private MyFunctions fx = new MyFunctions();

	private ResultsTable res = new ResultsTable();

	public boolean setup(String arg) {
		// If any Rois are not selected, abort.
		if (! dg.checkBeads() || ! dg.beadInformation3d())
			return false;
		imp = dg.imp;
		imp.setSlice(1);
		IJ.register(Generate_3D_information.class);
		return true;
	}

	@Override
	public void run(String arg) {
		if (!setup(arg))
			return;

		// Start processing
		ij.IJ.run(imp, "Select None", "");

		double[][] sgnl = new double[dg.nrois][dg.nslices];
		double[][] wph = new double[dg.nrois][dg.nslices];
		
		double sSum = 0;
		Rectangle roi;
		double[] results;
		
		for (int s = 1; s <= dg.nslices; s++) {
			imp.setSlice(s);
			ip = imp.getProcessor().duplicate();

			// build new frequency gatted image
			ImageProcessor lpip = ip.duplicate();
			fx.gblur.blur(ip, 0.5);
			fx.gblur.blur(lpip, dg.fwhm * 2);
			int v;
			for (int i = 0; i < ip.getWidth(); i++) {
				for (int j = 0; j < ip.getHeight(); j++) {
					v = ip.get(i, j) - lpip.get(i, j);
					if (v >= 0)
						ip.set(i, j, v);
					else
						ip.set(i, j, 0);
				}
			}

			for (int r = 0; r < dg.rois.length; r++) {
				roi = dg.rois[r].getBounds();
				results = fx.getParticleForCalibration(ip, dg, roi.x, roi.x
						+ roi.width, roi.y, roi.y + roi.height);
				sgnl[r][s - 1] = results[0];
				wph[r][s - 1] = results[9];
				sSum += results[0];
			}
		}

		for (int s = 0; s < dg.nslices; s++) {
			res.incrementCounter();
			for(int r = 0; r < dg.rois.length; r++){
				res.addValue("No." + (r+1) , wph[r][s]);
			}
		}
		res.show("3D Information");
	}
}